package com.example.demo.api;

import com.example.demo.entity.User;
import com.example.demo.game.Match;
import com.example.demo.game.MatchRequest;
import com.example.demo.game.MatchResponse;
import com.example.demo.game.OnlineUserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author CY
 * @date 2023/04/03 09:48
 **/
@Component
public class MatchAPI extends TextWebSocketHandler {
    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private OnlineUserMapper onlineUserMapper;
    @Autowired
    private Match match;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线
        //1.获取当前用户的信息;
        try {
            final User user = (User) session.getAttributes().get("user");
            //判断重复登录
            final WebSocketSession gameHall = onlineUserMapper.getGameHall(user.getUserId());
            if (gameHall == null) {
                final MatchResponse matchResponse = new MatchResponse();
                matchResponse.setOk(false);
                matchResponse.setReason("当前禁止多开");
                session.sendMessage(new TextMessage(mapper.writeValueAsString(matchResponse)));
                session.close();
                return;
            }

            onlineUserMapper.enterGameHall(user.getUserId(), session);
            System.out.println("玩家" + user.getUsername() + "进入游戏大厅:");
        } catch (Exception e) {
            e.printStackTrace();
            final MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("你未登录!不能进行后续匹配功能!");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        final String payload = message.getPayload();
        final MatchRequest request = mapper.readValue(payload, MatchRequest.class);
        final MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")) {
            match.add(user);
            response.setOk(true);
            response.setMessage("startMatch");

        } else if (request.getMessage().equals("stopMatch")) {
            match.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        } else {
            response.setOk(false);
            response.setReason("非法的匹配请求!");
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            final User user = (User) session.getAttributes().get("user");
            final WebSocketSession tmpSession = onlineUserMapper.getGameHall(user.getUserId());
            if (tmpSession == null) {
                onlineUserMapper.exitGameHall(user.getUserId());
            }
            match.remove(user);
        } catch (Exception e) {
            e.printStackTrace();
            final MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("你未登录!不能进行后续匹配功能!");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            final User user = (User) session.getAttributes().get("user");
            final WebSocketSession tmpSession = onlineUserMapper.getGameHall(user.getUserId());
            if (tmpSession == null) {
                onlineUserMapper.exitGameHall(user.getUserId());
            }
            match.remove(user);
        } catch (Exception e) {
            e.printStackTrace();
            final MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("你未登录!不能进行后续匹配功能!");
            session.sendMessage(new TextMessage(mapper.writeValueAsString(matchResponse)));
        }
    }
}
